package com.atguigu.tingshu.user.config;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import com.atguigu.tingshu.user.config.properties.WxAutoProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.integration.annotation.Gateway;
import org.springframework.security.jwt.crypto.sign.RsaSigner;
import org.springframework.security.rsa.crypto.KeyStoreKeyFactory;

import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.interfaces.RSAPrivateKey;

@Configuration //微信的自动配置类
@EnableConfigurationProperties(WxAutoProperties.class)
public class WxAppConfiguration {


    @Autowired
    private WxAutoProperties wxAutoProperties;

    /**
     * 定义WxService的Bean对象
     */
    @Bean
    public WxMaService wxMaService(){
        //1.创建WxMaService接口的对象
        WxMaService wxMaService = new WxMaServiceImpl();
        //2.创建一个微信的配置对象
        WxMaDefaultConfigImpl wxMaDefaultConfig = new WxMaDefaultConfigImpl();
        wxMaDefaultConfig.setAppid(wxAutoProperties.getAppId());
        wxMaDefaultConfig.setSecret(wxAutoProperties.getAppSecret());
        //3.将配置对象放到WxMaService中
        wxMaService.setWxMaConfig(wxMaDefaultConfig);
        return wxMaService;
    }

    /**
     * 定义RSA签名的Bean对象
     * //传统方式：
     *      String token = UUID.randomUUID().toString().replaceAll("-","");
     *      token = token + openid + userInfo.getId(); //token是一个有jwt生成的令牌
     * 		RSA:非对称加密方式 内有两把钥匙 (  公钥 (加密和验签) 私钥 ( 解密 (加签：防止数据被篡改) )  )
     * 		    加签：为了防止数据被篡改
     * 		    加密：为了防止数据被篡改  对敏感数据做保护的
     * 		对称加密（一把钥匙）
     *
     */
    @Bean
    public RsaSigner rsaSigner(){
        //1.读取RSA证书
        ClassPathResource classPathResource = new ClassPathResource("tingshu.jks");
        //2.创建一个工厂对象
        KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(classPathResource, "tingshu".toCharArray());

        //3.从工厂中获取钥匙对(公钥和私钥)
        KeyPair keyPair = keyStoreKeyFactory.getKeyPair("tingshu", "tingshu".toCharArray());

        //4.从钥匙对中获取私钥
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();

        RsaSigner rsaSigner = new RsaSigner(privateKey);
        return rsaSigner;
    }
}
